# -*- coding: utf-8 -*-

import json
import logging
import hashlib
import secrets
from datetime import datetime, timedelta
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import AccessDenied, UserError
import jwt

_logger = logging.getLogger(__name__)


class AuthController(http.Controller):
    """认证控制器 - 模仿若依登录认证"""

    @http.route('/api/auth/login', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def login(self, **kwargs):
        """用户登录接口"""
        try:
            # 从 JSON RPC 参数中获取数据
            username = kwargs.get('username')
            password = kwargs.get('password')
            code = kwargs.get('code')  # 验证码
            uuid = kwargs.get('uuid')  # 验证码UUID
            
            if not username or not password:
                return {
                    'code': 500,
                    'msg': '用户名和密码不能为空',
                    'data': None
                }
            
            # 这里可以添加验证码验证逻辑
            # if not self._verify_captcha(code, uuid):
            #     return {
            #         'code': 500,
            #         'msg': '验证码错误',
            #         'data': None
            #     }
            
            # 验证用户名密码
            user = self._authenticate_user(username, password)
            if not user:
                return {
                    'code': 500,
                    'msg': '用户名或密码错误',
                    'data': None
                }
            
            # 检查用户状态
            if user.status == '1':
                return {
                    'code': 500,
                    'msg': '用户已被停用，请联系管理员',
                    'data': None
                }
            
            # 登录信息在 _authenticate_user 中已更新
            
            # 生成JWT token
            token = self._generate_jwt_token(user)
            
            # 获取用户信息
            user_info = self._get_user_info(user)
            
            return {
                'code': 200,
                'msg': '登录成功',
                'data': {
                    'token': token,
                    'user': user_info
                }
            }
            
        except Exception as e:
            _logger.error(f"登录异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'登录失败: {str(e)}',
                'data': None
            }

    @http.route('/api/auth/getInfo', type='json', auth='none', methods=['GET', 'POST'], csrf=False, cors='*')
    def get_info(self, **kwargs):
        """获取用户信息"""
        try:
            # 验证token
            device_user = self._verify_token()
            if not device_user:
                return {
                    'code': 401,
                    'msg': '无效的访问令牌',
                    'data': None
                }
            
            _logger.info(f"获取用户信息，用户: {device_user.username}, 是否admin: {device_user.is_admin}")
            
            # 获取用户信息
            user_info = self._get_user_info(device_user)
            
            # 获取用户权限
            permissions = self._get_user_permissions(device_user)
            
            # 获取用户角色
            roles = device_user.role_ids.mapped('code')
            
            _logger.info(f"用户权限数量: {len(permissions)}, 角色数量: {len(roles)}")
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'user': user_info,
                    'roles': roles,
                    'permissions': permissions
                }
            }
            
        except Exception as e:
            _logger.error(f"获取用户信息异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'获取用户信息失败: {str(e)}',
                'data': None
            }

    @http.route('/api/auth/getRouters', type='json', auth='none', methods=['GET', 'POST'], csrf=False, cors='*')
    def get_routers(self, **kwargs):
        """获取路由信息"""
        try:
            # 验证token
            device_user = self._verify_token()
            if not device_user:
                return {
                    'code': 401,
                    'msg': '无效的访问令牌',
                    'data': None
                }
            
            _logger.info(f"获取路由信息，用户: {device_user.username}, 是否admin: {device_user.is_admin}")
            
            # 先检查菜单权限表是否有数据
            all_menus = request.env['device.menu.permission'].sudo().search([])
            _logger.info(f"菜单权限表总共有 {len(all_menus)} 条记录")
            
            if all_menus:
                _logger.info("菜单权限详情（前5条）:")
                for menu in all_menus[:5]:
                    _logger.info(f"  ID: {menu.id}, 名称: {menu.name}, 路径: {menu.path}, 激活: {menu.active}")
            
            # 获取用户菜单权限
            if device_user.is_admin:
                # admin用户获取所有菜单权限
                menu_permissions = all_menus
                _logger.info(f"admin用户，获取所有 {len(menu_permissions)} 个菜单权限")
            else:
                # 普通用户获取角色分配的菜单权限
                menu_permissions = device_user.role_ids.mapped('menu_permission_ids')
                _logger.info(f"普通用户，获取 {len(menu_permissions)} 个菜单权限")
            
            # 构建路由树
            if menu_permissions:
                menu_tree = request.env['device.menu.permission'].sudo().get_menu_tree(menu_permissions.ids)
                _logger.info(f"构建的菜单树，根节点数量: {len(menu_tree) if menu_tree else 0}")
            else:
                menu_tree = []
                _logger.info("没有菜单权限，返回空数组")
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': menu_tree
            }
            
        except Exception as e:
            _logger.error(f"获取路由信息异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'获取路由信息失败: {str(e)}',
                'data': None
            }

    @http.route('/api/auth/logout', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def logout(self, **kwargs):
        """用户登出"""
        try:
            # 这里可以添加token注销逻辑，如加入黑名单等
            return {
                'code': 200,
                'msg': '退出成功',
                'data': None
            }
        except Exception as e:
            _logger.error(f"登出异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'登出失败: {str(e)}',
                'data': None
            }

    @http.route('/api/auth/captchaImage', type='json', auth='none', methods=['GET'], csrf=False, cors='*')
    def captcha_image(self, **kwargs):
        """获取验证码图片"""
        try:
            # 这里可以集成验证码生成库
            # 简单起见，返回一个mock的验证码信息
            import uuid
            captcha_uuid = str(uuid.uuid4())
            
            return {
                'code': 200,
                'msg': '操作成功',
                'data': {
                    'uuid': captcha_uuid,
                    'img': '...',  # Base64编码的图片
                    'captchaEnabled': True
                }
            }
        except Exception as e:
            _logger.error(f"获取验证码异常: {str(e)}")
            return {
                'code': 500,
                'msg': f'获取验证码失败: {str(e)}',
                'data': None
            }

    def _authenticate_user(self, username, password):
        """验证用户名密码 - 使用独立的 device.user 表"""
        try:
            # 确保参数类型正确
            username = str(username) if username else None
            password = str(password) if password else None
            
            _logger.info(f"Device用户登录尝试: username={username}")
            
            # 查找 Device 用户
            user = request.env['device.user'].sudo().search([
                ('username', '=', username),
                ('status', '=', '0'),  # 正常状态
                ('del_flag', '=', '0')  # 未删除
            ], limit=1)
            
            if not user:
                _logger.info(f"Device用户不存在: {username}")
                return None
            
            # 验证密码
            if user.check_password(password):
                _logger.info(f"Device用户 {username} 认证成功")
                # 更新登录信息
                user.update_login_info(request.httprequest.remote_addr)
                return user
            else:
                _logger.info(f"Device用户 {username} 密码错误")
                return None
                
        except Exception as e:
            _logger.error(f"Device用户认证异常: {str(e)}")
            return None

    def _generate_jwt_token(self, user):
        """生成JWT token"""
        try:
            payload = {
                'user_id': user.id,
                'username': user.username,
                'exp': datetime.utcnow() + timedelta(hours=request.env['device.api.config'].sudo().get_jwt_expire_hours()),
                'iat': datetime.utcnow()
            }
            
            secret_key = request.env['device.api.config'].sudo().get_jwt_secret()
            token = jwt.encode(payload, secret_key, algorithm='HS256')
            
            return token
        except Exception as e:
            _logger.error(f"生成token异常: {str(e)}")
            return None

    def _verify_token(self):
        """验证JWT token"""
        try:
            # 从请求头获取token
            auth_header = request.httprequest.headers.get('Authorization')
            if not auth_header or not auth_header.startswith('Bearer '):
                return None
            
            token = auth_header.split(' ')[1]
            
            # 解码token
            secret_key = request.env['device.api.config'].sudo().get_jwt_secret()
            payload = jwt.decode(token, secret_key, algorithms=['HS256'])
            
            # 获取用户
            user = request.env['device.user'].sudo().browse(payload['user_id'])
            if user.exists() and user.status == '0' and user.del_flag == '0':
                return user
            
            return None
        except jwt.ExpiredSignatureError:
            return None
        except jwt.InvalidTokenError:
            return None
        except Exception as e:
            _logger.error(f"验证token异常: {str(e)}")
            return None

    def _get_user_info(self, user):
        """获取 Device 用户信息"""
        return {
            'userId': user.id,
            'userName': user.username,
            'nickName': user.nick_name or user.username,
            'email': user.email or '',
            'phonenumber': user.phone or '',
            'sex': '0',  # 可以扩展性别字段
            'avatar': user.avatar or '',
            'admin': user.is_admin,
            'dept': {
                'deptId': user.department_id.id,
                'deptName': user.department_id.name,
                'parentId': user.department_id.parent_id.id if user.department_id.parent_id else None
            } if user.department_id else None,
            'roles': [{'roleId': role.id, 'roleName': role.name, 'roleKey': role.code} for role in user.role_ids],
            'posts': [{'postId': post.id, 'postName': post.name, 'postCode': post.code} for post in user.post_ids]
        }

    def _get_user_permissions(self, device_user):
        """获取用户权限列表"""
        if device_user.is_admin:
            # 超级管理员拥有所有权限
            # permissions = request.env['device.permission'].sudo().search([])
            # _logger.info(f"admin用户，获取所有 {len(permissions)} 个权限")
            return ["*:*:*"]
        
        # 普通用户权限
        role_permissions = device_user.role_ids.mapped('permission_ids')
        _logger.info(f"普通用户，从角色获取 {len(role_permissions)} 个权限")
        return role_permissions.mapped('perms')
